package ortustve.media.fanart;

import java.util.logging.Level;
import java.util.logging.Logger;
import ortustve.*;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sagex.api.Configuration;
import sagex.api.MediaFileAPI;
import sagex.api.ShowAPI;




@SuppressWarnings("unused")
public class PhoenixFanart extends ortustve.ortusvars implements IFanartProvider {

    private String seperator = File.separator;
    private String CentralTVFolder = phoenix.api.GetFanartCentralFolder() + seperator + "TV" + seperator;
	
	// All calls below are temporary until they are added to phoenix api. 
	// The return of Season calls returns series if no season is available. Always use phoenix
	// HasFanart calls before hand in studio to avoid nulls.


public String GetFanartFolder() {
    
    String fanartfolder = Configuration.GetProperty("ortus/fanart/folder", null);
    
    if ( fanartfolder == null ) {
        fanartfolder  = System.getProperty("user.dir") + seperator + "STVs" + seperator + "SageTV3" + seperator + "Ortus" + seperator + "Fanart";
        File df = new File(fanartfolder);
        if ( ! df.exists() ) {
            df.mkdir();
        }
    }

    return fanartfolder;
}

public void SetFanartFolder(String folder) {

    Configuration.SetProperty("ortus/fanart/folder", folder);

    File df = new File(folder);
    if ( ! df.exists() ) {
        df.mkdir();
    }
    
    return;
}

public String GetCastFanartPoster(String castname){
      ortustve.api.DebugLog(TRACE2, " GetCastFanartPoster: fanart for: " + castname);
      String NewFanart = null;
      File directory = new File(GetFanartFolder() + java.io.File.separator + "Cast" + java.io.File.separator +  castname);
      File[] AllFanart = directory.listFiles(new ImageFilter());
      if(AllFanart != null) {
         NewFanart = AllFanart[0].getAbsolutePath();
      }

      ortustve.api.DebugLog(TRACE2, " GetCastFanartPoster: returning: " + NewFanart);
      return NewFanart;
}

public String GetSeasonFanartPoster(Object MediaObject){
  	  String NewFanart = "none";
	  File directory = new File(phoenix.api.GetFanartPosterPath(MediaObject));
      File[] AllFanart = directory.listFiles(new ImageFilter());
       if(AllFanart != null)
        {NewFanart = AllFanart[0].toString();}
       else
       {NewFanart = GetSeriesFanartPoster(MediaObject);}

      return NewFanart;}
 
 public String GetSeriesFanartPoster(Object MediaObject){
	 String NewFanart = null;
	 String Title = ortustve.api.GetShowTitle(MediaObject);
	 String SeriesPath = phoenix.api.GetFanartCentralFolder() + "\\TV\\" + Title + "\\Posters";
	 File directory = new File(SeriesPath);
	 File[] AllFanart = directory.listFiles(new ImageFilter());
	  if(AllFanart != null)
      {NewFanart = AllFanart[0].toString();}

     return NewFanart;}
 
 public String GetSeasonFanartBanner(Object MediaObject){
     String NewFanart = "none";
	 File directory = new File(phoenix.api.GetFanartBannerPath(MediaObject));
     File[] AllFanart = directory.listFiles(new ImageFilter());
      if(AllFanart != null){
       NewFanart = AllFanart[0].toString();}
      else{
    	NewFanart = GetSeriesFanartPoster(MediaObject);}
	
     return NewFanart;}
       
public String GetSeriesFanartBanner(Object MediaObject){
	 String NewFanart = null;
	 String Title = ortustve.api.GetShowTitle(MediaObject);
	 String SeriesPath = phoenix.api.GetFanartCentralFolder() + "\\TV\\" + Title + "\\Banners";
	 File directory = new File(SeriesPath);
	 File[] AllFanart = directory.listFiles(new ImageFilter());
	  if(AllFanart != null){
       NewFanart = AllFanart[0].toString();}

     return NewFanart;}

//public File[] GetSeasonFanartPosters(Object MediaObject){
//	  File directory = new File(phoenix.api.GetFanartPosterPath(MediaObject));
//      File[] AllFanart = directory.listFiles(new ImageFilter());
//       if(AllFanart != null){
//       return AllFanart;}
//      else{
//       AllFanart = GetSeriesFanartPosters(MediaObject);}
//
//      return AllFanart;}
public File[] GetSeriesFanartPosters(Object MediaObject)
{
	 String Title = ortustve.api.GetShowTitle(MediaObject);
	 String SeriesPath = phoenix.api.GetFanartCentralFolder() + "\\TV\\" + Title + "\\Posters";
	 File directory = new File(SeriesPath);
	 File[] AllFanart = directory.listFiles(new ImageFilter());
	 if(AllFanart != null){
       return AllFanart;}
	
     return AllFanart = null;}
        
public List<String> GetMenuBackgrounds(String Menutype)
{

	 String Path = phoenix.api.GetFanartCentralFolder() + "\\" + Menutype;
	 File directory = new File(Path);
	 File[] AllDirectories = directory.listFiles(new DirectoryFilter());
     ArrayList<String> AllFanart = new ArrayList<String>();
	 ortustve.api.DebugLog(3,"Directory: " + Path + " Size of Subfolders:" + AllDirectories.length);
	  if(AllDirectories != null){
        for(int i =0; i < AllDirectories.length - 3;i++){
		String SubPath = AllDirectories[i].toString() + "\\Backgrounds" ;
		ortustve.api.DebugLog(3,"Adding + SubDirectory: "+ i + SubPath);
		File tempbglist = new File(SubPath);
		 if (tempbglist.isDirectory()){
		  File[] tempbgs = tempbglist.listFiles(new ImageFilter());
	     if (tempbgs != null && tempbgs.length != 0){
		  AllFanart.add(tempbgs[0].toString());}}}

        return AllFanart;}
    
	 ortustve.api.DebugLog(1,"AllFanart equals null");
	 return  null;}
        
public String GetMenuBackground(String MenuType) {
	if (MenuType.contains("tv"))
	 { MenuType = "TV";}
	if (MenuType.contains("movie"))
	 { MenuType = "Movies"; }
	if (MenuType.contains("music"))
	 { MenuType = "Music";}
	String Path = phoenix.api.GetFanartCentralFolder() + "\\" + MenuType;
	File directory = new File(Path);
	File[] AllDirectories = directory.listFiles(new DirectoryFilter());
	File [] AllFanart = null; ortustve.api.DebugLog(3,"Directory: " + Path);
	 if(AllDirectories != null) {
		for(int i =0;AllFanart == null && i < AllDirectories.length ;i++){
			int randint = phoenix.api.GetRandomNumber(AllDirectories.length);
			String SubPath = AllDirectories[randint].toString()+ "\\Backgrounds" ;
			ortustve.api.DebugLog(3,"SubDirectory: " + SubPath);
			File subdirectory = new File(SubPath);
			AllFanart = subdirectory.listFiles(new ImageFilter()); }

        return AllFanart[0].toString();  }
	    ortustve.api.DebugLog(1,"AllFanart equals null");

    return null; }

// Creates Fanart Posters for all folder.jpg's for a given Array of movies. Will check to make sure no fanart poster and baackgrounds
// exist and then will create Movie folder and poster folder based off @MediaTitle same method as BMI uses to create fanart.
// This allows those not wanting to use BMI to use newer stvi's which require the fanart structure.

// @ MediaObjects = Array of mediaobjects with possible folder.jpg's. Jpeg does not have to be called folder.jpg just must reside in main movie folder.
// Will move multiple jpg's if they exist. Background fanart must contain the word "background" in the name of the jpg.

public void CreateFanartFromJPG(Object[] MediaObjects) {
	if (MediaObjects.length > 0){
      for(int j = 0;j < MediaObjects.length;j++){
       
     Object MediaObject = MediaObjects[j];

    String Title = GetSafeTitle(MediaObject);
    Boolean hasfanart = phoenix.api.HasFanartPoster(MediaObject);
	 if (Title != null && Title.length() != 0 && hasfanart == false){
	// commented out for thumbs maybe at a later date not complete need to evaluate further
	//String SThumb = MediaFileAPI.GetThumbnail(MediaObject).toString();
	//Global.ortus.api.DebugLog("Before Stringing  " + SThumb );
	//SThumb = SThumb.substring(SThumb.indexOf("[")+1,SThumb.indexOf("#"));
	//File FThumb = new File(SThumb);
	//Global.ortus.api.DebugLog("After Stringing" + SThumb);
		// Again commented out for thumbs
		//if (FThumb.isFile()){
		//Global.ortus.api.DebugLog("IsFile = true");
		//boolean success = FThumb.renameTo(new File(FDirectory,FThumb.getName()));}

	 File PosterDirectory = new File(phoenix.api.GetFanartCentralFolder() + "\\Movies\\" + Title + "\\Posters");
	 File BackgroundDirectory = new File(phoenix.api.GetFanartCentralFolder() + "\\Movies\\" + Title + "\\Backgrounds");
     File jpgfolder = new File(MediaFileAPI.GetParentDirectory(MediaObject).toString()+"\\");
	 File[] jpegs = jpgfolder.listFiles(new ImageFilter());
	 if (jpegs.length != 0 && jpegs != null){
	   if (PosterDirectory.exists()== false){
             ortustve.api.DebugLog(3,"Making New Directory " + PosterDirectory);
             boolean success1 = PosterDirectory.mkdirs();
         if(success1 == true){
           	ortustve.api.DebugLog(3,"Movie Directory made " + PosterDirectory);}
         if (success1 == false){
           ortustve.api.DebugLog(1,"Movie Directory failed creation " + PosterDirectory);}}
         for (int i=0;i <jpegs.length;i++){
            File Folderjpg = jpegs[i];
            ortustve.api.DebugLog(3,"Folderjpg exist " + Folderjpg);
         if (PosterDirectory.exists()&& !Folderjpg.toString().toLowerCase().contains("background") && !Folderjpg.toString().toLowerCase().contains("fanart")){
                try {
                    copy(Folderjpg, new File(PosterDirectory.toString() + Folderjpg.toString().substring(Folderjpg.toString().lastIndexOf("\\"))));
                } catch (Exception ex) {}
             boolean success3 = new File(PosterDirectory.toString() + Folderjpg.toString().substring(Folderjpg.toString().lastIndexOf("\\"))).exists();
                if (success3 == true);{
            	ortustve.api.DebugLog(3,"File copied");}
                if(success3 == false){
            	ortustve.api.DebugLog(1,"File not copied");}}
         else if (Folderjpg.toString().toLowerCase().contains("background") || Folderjpg.toString().toLowerCase().contains("fanart")){
                ortustve.api.DebugLog(3,"jpg is background checking for background directory");
                if (BackgroundDirectory.exists()== false){
                ortustve.api.DebugLog(3,"Making New Background Directory " + BackgroundDirectory);
               boolean success1 = BackgroundDirectory.mkdirs();
               if(success1 == true){
             	ortustve.api.DebugLog(3,"Movie Directory made " + BackgroundDirectory);}
               if (success1 == false){
                ortustve.api.DebugLog(1,"Movie Directory failed creation " + BackgroundDirectory);}}
                try {
                    copy(Folderjpg, new File(BackgroundDirectory.toString() + Folderjpg.toString().substring(Folderjpg.toString().lastIndexOf("\\"))));
                } catch (Exception ex) {}
               boolean success3 = new File(PosterDirectory.toString() + Folderjpg.toString().substring(Folderjpg.toString().lastIndexOf("\\"))).exists();
                if (success3 == true);{
            	ortustve.api.DebugLog(3,"File copied");}
                if(success3 == false){
            	ortustve.api.DebugLog(1,"File not copied");}}

         if (!PosterDirectory.exists() ){
          ortustve.api.DebugLog(1,"Cannot Create Folder structure error in Title return");}}}

     else{
          ortustve.api.DebugLog(1, "No folderjpegs found for title " + Title);}}

    else if (Title == null || Title.length() == 0 && hasfanart == false){
	    ortustve.api.DebugLog(1,"No Poster Created for Movie not title found");}
    else if (hasfanart == true){
        ortustve.api.DebugLog(3,"Has Fanart Poster no jpeg conversion needed" + Title);}}}}

// Returns a ArrayList of strings of "MediaTitles" for fanart folders that exist but there is no matching title in the SageDB.
// Can then be passed to FanartCleanupMove to move this files.
//@ Object[] mediafiles passed from Sage ie. GetMediaFiles()
//@ String Type = "Movies" or "TV" for type of media files being passed.

public Map<String,List> GetFanartCleanupList(Object[] MediaObjects,String Type)
{
    ArrayList<String> Titles = new ArrayList<String>();
    for(int a =0;a<MediaObjects.length;a++){
        Titles.add(a, GetSafeTitle(MediaObjects[a]));
    }
    String Path = phoenix.api.GetFanartCentralFolder() + "\\" + Type;
    File directory = new File(Path);
	File[] AllDirectories = directory.listFiles(new DirectoryFilter());
	Map<String,List> NoFiles = new HashMapImpl();
   
        if(AllDirectories != null && AllDirectories.length != 0){
         for (int i=0;i<AllDirectories.length;i++){
             String CurrDirectory = AllDirectories[i].toString();
             CurrDirectory = CurrDirectory.substring(CurrDirectory.lastIndexOf("\\")+1);
             ortustve.api.DebugLog(3, "Current Directory searching titles: " + CurrDirectory);
             boolean found = false;
             for (int j = 0;j<Titles.size() && found == false;j++){
                 String Title = Titles.get(j);
                 if(Title.equalsIgnoreCase(CurrDirectory)){
                 ortustve.api.DebugLog(3, "Title Found: " + CurrDirectory);
                 Titles.remove(Titles.get(j));
                 ortustve.api.DebugLog(5,"Removing found title : " + Titles.size());
                 found = true;
             }
             else{
                 ortustve.api.DebugLog(5, "Next Title  " + j);
             }}
             if (found == false){
                  ortustve.api.DebugLog(3, "Fanart has no title associated added to list : " + CurrDirectory);
                String Key = AllDirectories[i].toString();
                NoFiles.put(Key,ortustve.util.file.GetFolderDetail(Key));
                          
             }}}

       return NoFiles;
}

// Takes ArrayList from GetFanartCleanupList only!!! Moves those files to default folder of
//  "centralfanart folder//unused//ddyymm//type"
// Moves all folders passed but keeps original folder structure
//@ ArrayList<String> - accepts arraylist passed from GetFanartCleanupList
//@ Type - accepts type of media ("TV", "Movies")

public void FanartCleanupMove (HashMap<String,List> FoldersMap,String Type){
          Object[] Folders = api.toArray(FoldersMap);
          for (int i =0;i<Folders.length;i++){
          String Date = getDateTime();
          if(Type.equals("All")){
              if(Folders[i].toString().contains("TV")){
                  Type = "TV";
              }
              else {
                  Type = "Movies";
              }
          }
          String Folder = phoenix.api.GetFanartCentralFolder() + "\\unused\\" + Date +"\\" + Type;
          File Directory = new File(Folder);
          Directory.mkdirs();
          if (Directory.canRead() && Directory.canWrite()){
          ortustve.api.DebugLog(3, "Folders Files being moved to: " + Folder);
          File ODirectoryF = new File(Folders[i].toString());
           boolean success = ODirectoryF.renameTo(new File(Directory, ODirectoryF.getName()));
             if (success==true) {
             ortustve.api.DebugLog(3,"Directories moved " + Folder);}
             else {
             ortustve.api.DebugLog(3, "Directory failed to move : "+ Folder);
             }}
          else{
              ortustve.api.DebugLog(1,"Read/Write access denied");}}}

public String GetShowThumbnail(Object MediaObject){
        int MediaID = MediaFileAPI.GetMediaFileID(MediaObject);
        List results=ortustve.api.executeSQLQuery("Select mediatitle,season,episode FROM sage.mediatv WHERE mediaid=" + MediaID);
        String path = "";
        if(!results.isEmpty()){
        path = CentralTVFolder + results.get(0)+ seperator + "Thumbnails" + results.get(0) +"S" +
                results.get(2)+"E"+results.get(3)+".jpg";
        File thumb = new File(path);
        if(!thumb.exists()){
        path = "";
        }
        }
       return path;
}




public void FanartCleanupDelete ( HashMap<String,List> FoldersMap){
          Object[] Folders = api.toArray(FoldersMap);
          for (int i =0;i<Folders.length;i++){
          File CurrDirectory = new File(Folders[i].toString());
          ortustve.api.DebugLog(3,"Directory to delete " + CurrDirectory);
          if (CurrDirectory.canRead() && CurrDirectory.canWrite()){
                delete(CurrDirectory);
                CurrDirectory.delete();}

          else {
              ortustve.api.DebugLog(1, "Cannot get read and write acess");
          }}}
   
public void copy(File src, File dst) {
        InputStream in = null;
        try {
            in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (Exception ex) {
            Logger.getLogger(PhoenixFanart.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                in.close();
            } catch (Exception ex) {
                Logger.getLogger(PhoenixFanart.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
}
private static String GetSafeTitle(Object MediaObject){
    String Title = api.GetMediaTitle(MediaObject);
    if (Title == null || Title.length() == 0){
       Title = ShowAPI.GetShowEpisode(MediaObject);
          }
    return sagex.phoenix.fanart.FanartUtil.createSafeTitle(Title);
}
private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyMMdd") ;
        Date date = new Date();
        return dateFormat.format(date);
    }

private void delete(File folder)
{
        if(folder.exists())
        {
                ortustve.api.DebugLog(3, "Folder Exist");
                File[] files = folder.listFiles();
                ortustve.api.DebugLog(3, "Size of files in Folder" + folder + folder.length());
                for(int i=0; i < files .length; i++)
                {
                        File oFileCur = files [i];
                        if(oFileCur.isDirectory())
                        {
                                // call itself to delete the contents of the current folder
                                delete(oFileCur);
                        }
                        oFileCur.delete();
                }
        }

}

	@Override
	public String GetFanartPoster(Object mediafile) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public List<Object> GetFanartPosters(Object mediafile) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public String GetFanartBanner(Object mediafile) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public List<Object> GetFanartBanners(Object mediafile) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public String GetFanartBackground(Object mediafile) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public List<Object> GetFanartBackgrounds(Object mediafile) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public List<Object> GetFanartRandom(List<Object> fanart) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public List<Object> GetSeasonFanartPosters(Object MediaObject) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public List<Object> GetSeasonFanartBanners(Object MediaObject) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

    private class HashMapImpl extends HashMap<String, List> {

        public HashMapImpl() {
        }
    }
}
class ImageFilter implements FileFilter
{  
    @Override
   public boolean accept(File file)  
   {  
      return file.getName().contains("jpg");  
   }  
}

class DirectoryFilter implements FileFilter
{
    @Override
   public boolean accept(File file)
   {  
      return file.isDirectory();
   }
}




